#ifndef GBK_UTF8_H
#define GBK_UTF8_H

#include <string>
#include <iconv.h>
#include <errno.h>
#include <cstring>

class GbkToUtf8 {
public:
    static std::string convert(const std::string& gbk_str) {
        if(gbk_str.empty()) return "";

        iconv_t cd = iconv_open("UTF-8", "GBK");
        if (cd == (iconv_t)-1) {
            return ""; // 转换器创建失败
        }

        const char* in_buf = gbk_str.c_str();
        size_t in_left = gbk_str.length();
        
        // UTF-8可能会比GBK占用更多空间
        size_t out_len = in_left * 3 + 1;
        char* out_buf = new char[out_len];
        char* out_ptr = out_buf;
        size_t out_left = out_len;

        // 进行转换
        size_t result = iconv(cd, const_cast<char**>(&in_buf), &in_left, &out_ptr, &out_left);
        
        std::string utf8_str;
        if (result != (size_t)-1) {
            *out_ptr = 0;
            utf8_str = std::string(out_buf);
        }

        delete[] out_buf;
        iconv_close(cd);
        
        return utf8_str;
    }
};

#endif 